Component({
  properties: {
    show: Boolean,
    cameraPosition: {
      type: String,
      value: 'back',
    },
    flashMode: {
      type: String,
      value: 'off',
    }
  },

  data: {
    cameraContext: null,
    isProcessing:false
  },
   lifetimes: {
    ready() {
      this.createCameraContext();
    }
  },
  methods: {
    createCameraContext: function () {
      let that = this
      const cameraContext = wx.createCameraContext();
      that.setData({
        cameraContext: cameraContext
      });
    },

    // 拍照
    takePhoto: function () {
      if (this.data.isProcessing) return;
      const that = this;
      try {
        this.setData({
          isProcessing: true
        });
        wx.showLoading({
          title: '拍摄中...',
        });
        // 配置高精度拍照参数
        const cameraConfig = {
          quality: 'high',  // 高质量图片
          success: (res) => {
            wx.hideLoading();
            // 获取图片临时路径
            const tempImagePath = res.tempImagePath;
            // 使用高精度裁剪功能
            this.cropImage(tempImagePath);
          },
          fail: (err) => {
            console.error('拍照失败:', err);
            wx.hideLoading();
            wx.showToast({
              title: '拍照失败',
              icon: 'none'
            });
            that.setData({
              isProcessing: false
            });
          }
        };
        // 执行拍照
        this.data.cameraContext.takePhoto(cameraConfig);
      } catch (error) {
        this.cameraError(err)
        that.setData({
          isProcessing: false
        });
      }
  
    },
      // 图像裁剪处理
  cropImage: function (imagePath) {
    console.log(3);
    wx.showLoading({
      title: '优化识别区域...',
    });

    // 获取手机屏幕尺寸
    const systemInfo = wx.getSystemInfoSync();
    const screenWidth = systemInfo.windowWidth;
    const screenHeight = systemInfo.windowHeight / 2;

    // 计算裁剪区域（取景框在屏幕中的位置）
    // 取景框宽度为680rpx，高度为300rpx
    const frameWidth = 650 * screenWidth / 750; // rpx转px
    const frameHeight = 300 * screenWidth / 750; // rpx转px
    // 计算裁剪区域的位置（居中）
    const left = (screenWidth - frameWidth) / 2;
    const top = (screenHeight - frameHeight) / 2;

    try {
      // 尝试进行精确裁剪
      this.cropWithWechatAPI(imagePath, left, top, frameWidth, frameHeight);
    } catch (error) {
      console.error('裁剪出错，使用原生API', error);
      this.useNativeImageEditor(imagePath);
    }
  },
  
  // 使用微信原生API进行裁剪
  cropWithWechatAPI: function (imagePath, left, top, width, height) {
    wx.compressImage({
      src: imagePath,
      quality: 90, // 高质量压缩
      success: (compressRes) => {
        const compressedPath = compressRes.tempFilePath;
        // 获取图像信息
        wx.getImageInfo({
          src: compressedPath,
          success: (imgInfo) => {
            // 计算裁剪区域的像素坐标
            const imgWidth = imgInfo.width;
            const imgHeight = imgInfo.height;

            // 计算实际裁剪比例
            const screenW = wx.getSystemInfoSync().windowWidth;
            const screenH = wx.getSystemInfoSync().windowHeight;

            // 计算屏幕上取景框与原始图片的比例关系
            const scaleX = imgWidth / screenW;
            const scaleY = imgHeight / screenH;

            // 转换裁剪坐标到图片坐标系统
            const cropX = left * scaleX;
            const cropY = top * scaleY;
            const cropW = width * scaleX;
            const cropH = height * scaleY;
            // 使用wx.cropImage API裁剪图片
            // 注意：部分平台可能不支持此API，需要进行兼容
            if (wx.cropImage) {
              wx.cropImage({
                src: compressedPath,
                cropScale: '1:1', // 可以根据需要调整
                x: cropX,
                y: cropY,
                width: cropW,
                height: cropH,
                success: (cropRes) => {
                  wx.hideLoading();
                  const croppedPath = cropRes.tempFilePath; 
                  this.triggerEvent('photoTaken',croppedPath); 
                  this.setData({
                    showCamera: false,
                    isProcessing: false,
                    searchType:false
                  });
                },
                fail: (err) => {
                  console.error('wx.cropImage失败:', err);
                  this.setData({
                    showCamera: false,
                    isProcessing: false
                  });
                  this.cameraError(err)
                  wx.hideLoading();
                }
              });
            }
          },
          fail: (err) => {
            console.error('获取图片信息失败:', err);
            this.setData({
              showCamera: false,
              isProcessing: false
            });
            this.cameraError(err)
            wx.hideLoading();
          }
        });
      },
      fail: (err) => {
        console.error('压缩图片失败:', err);
        this.cameraError(err)
        this.setData({
          showCamera: false,
          isProcessing: false
        });
        wx.hideLoading();
      }
    });
  },

  // 使用原生图片编辑器
  useNativeImageEditor: function (imagePath) {
    wx.editImage({
      src: imagePath,
      success: (res) => {
        wx.hideLoading();
        // 上传处理裁剪后的图片
        // this.uploadImage(res.tempFilePath);
        this.triggerEvent('photoTaken',croppedPath); 
        // 关闭相机界面
        this.setData({
          showCamera: false,
          isProcessing: false
        });
      },
      fail: (err) => {
        console.log('裁剪失败，使用原图:', err);
        wx.hideLoading();
        this.cameraError(err)
        this.setData({
          showCamera: false,
          isProcessing: false
        });
      }
    });
  },
    /**
     * 相机出错处理
     * @param {*} e 
     */
    cameraError: function (e) {
      console.error('相机错误:', e.detail);
      wx.showToast({
        title: '相机启动失败',
        icon: 'none'
      });
      this.triggerEvent('error', res.tempImagePath);
    },
    close() {
      this.triggerEvent('close');
    },

    onError(e) {
      wx.showToast({ title: '摄像头异常', icon: 'none' });
    }
  }
});
